package com.sptan.framework.config;

import com.sptan.framework.core.ResultEntity;
import com.sptan.framework.util.JSONUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 处理JWT认证过滤器中的异常.
 *
 * @author liupeng
 * @date 2024/5/5
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
        throws IOException {

        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());

        ResultEntity resultEntity = ResultEntity.error("认证登录失败");

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(JSONUtils.toJSONString(resultEntity).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
